﻿using System.Reflection;
using Autofac;
using Autofac.Extras.DynamicProxy;
using Infrastructure.UnitWork;
using TestDDD.Interceptors;

namespace TestDDD.Extensions
{
    public class APIAutofacRegister : Autofac.Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            var services = Assembly.GetExecutingAssembly()
                .GetTypes()
                .Where(t => t.IsClass && !t.IsGenericType && !t.IsAbstract && t.Name.EndsWith("Service"));
            builder.RegisterTypes([.. services]).AsImplementedInterfaces()
                .InstancePerLifetimeScope()
                .EnableInterfaceInterceptors()
                .InterceptedBy(typeof(TransactionInterceptor));

            var controllers = Assembly.GetExecutingAssembly()
                .GetTypes()
                .Where(t => t.IsClass && !t.IsGenericType && !t.IsAbstract && t.Name.EndsWith("Controller"));
            builder.RegisterTypes([.. controllers]).AsImplementedInterfaces()
                .InstancePerLifetimeScope();

            var interceptors = Assembly.GetExecutingAssembly()
            .GetTypes()
            .Where(t => t.IsClass && !t.IsGenericType && !t.IsAbstract && t.Name.EndsWith("Interceptor"));
            builder.RegisterTypes([.. interceptors])
                .InstancePerLifetimeScope();

            //var repositories = Assembly.GetExecutingAssembly()
            //    .GetTypes()
            //    .Where(t => t.IsClass && !t.IsGenericType && !t.IsAbstract && t.Name.EndsWith("Respository"));
            //builder.RegisterTypes([.. repositories]).AsImplementedInterfaces()
            //    .InstancePerLifetimeScope()
            //    .PropertiesAutowired();
        }
    }
}
